# encoding: utf-8

class GroupsThreadsController < ApplicationController

	before_filter :do_index, :only => [:show]
	before_filter :load_sidebar
	before_filter :require_login, :except => [:show]
	# GET /groups_threads/1
	# GET /groups_threads/1.xml
	def show
		@groups_thread = GroupsThread.find(params[:id])
		
		# ako je unesen nestandardni URL
		if @groups_thread.url != request.path then
			redirect_to @groups_thread.url
		end 
		
		# prekini izvodjenje ako nema dopustenja (inace dolazi do double render errora)
		return unless require_group_permission(@groups_thread.group)

		@groups_posts = @groups_thread.groups_posts.paginate :page => params[:page], :per_page => 10,:order => 'created_at'

		@meta_title = @groups_thread.title + " - " + @groups_thread.group.name
		@meta_description = @groups_thread.content.gsub(/<\/?[^>]*>/, "").gsub(/\[\/?[^\]]*\]/, "")

		# pracenje posjeta threadu
	  @groups_thread.visit current_member
	  
	end
	

	# GET /groups_threads/new
	# GET /groups_threads/new.xml
	def new
		@groups_thread = GroupsThread.new
		@groups_thread[:group_id] = params[:group_id]

		respond_to do |format|
			format.html # new.html.erb
			format.xml  { render :xml => @groups_thread }
		end
	end

	# GET /groups_threads/1/edit
	def edit
		@groups_thread = GroupsThread.find(params[:id])
		return unless require_admin_or_this_member @groups_thread.member
	end

	# POST /groups_threads
	# POST /groups_threads.xml
	def create
		@groups_thread = GroupsThread.new(params[:groups_thread])
		@groups_thread[:member_id] = current_member.id
		@groups_thread[:post_count] = 0
		if @groups_thread.save
		  
		  feed = Feed.new
      feed.content = @groups_thread
      feed.member = current_member
      feed.group = @groups_thread.group
      feed.save
      
      if @groups_thread.sticky
        @groups_thread.group.members.each do |member|
          UserMailer.new_sticky_thread(member, @groups_thread).deliver
        end
      end
      
			redirect_to(@groups_thread, :notice => 'Nova rasprava je stvorena.')
		else
			render :action => "new"
		end
	end

	# PUT /groups_threads/1
	# PUT /groups_threads/1.xml
	def update
		@groups_thread = GroupsThread.find(params[:id])
		return unless require_admin_or_this_member @groups_thread.member

		if @groups_thread.update_attributes(params[:groups_thread])
			redirect_to(@groups_thread, :notice => 'Rasprava je izmjenjena.')
		else
			render :action => "edit"
		end
	end

	# DELETE /groups_threads/1
	# DELETE /groups_threads/1.xml
	def destroy
		@groups_thread = GroupsThread.find(params[:id])
		return unless require_admin_or_this_member @groups_thread.member

		redirect_url = @groups_thread.group
		@groups_thread.destroy

		redirect_to(redirect_url)
	end
end
